package com.farm.util;

import com.iflytek.cloud.speech.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class IatTool {

    private static final Logger LOGGER = LoggerFactory.getLogger(IatTool.class);
    private StringBuilder curRet;
    private SpeechRecognizer recognizer;
    private CountDownLatch latch;

    public IatTool(String appId) {
        LOGGER.info("------Speech Utility init iat------");
        SpeechUtility.createUtility(SpeechConstant.APPID + "=" + appId);
    }

    public String RecognizePcmfileByte(byte[] buffer) {
        curRet = new StringBuilder();
        latch = new CountDownLatch(1); // 初始化CountDownLatch，设置计数为1

        try {
            if (recognizer == null) {
                recognizer = SpeechRecognizer.createRecognizer();
                recognizer.setParameter(SpeechConstant.AUDIO_SOURCE, "-1");
                recognizer.setParameter(SpeechConstant.RESULT_TYPE, "plain");
            }

            recognizer.startListening(recListener);
            if (buffer == null || buffer.length == 0) {
                LOGGER.error("no audio available!");
                recognizer.cancel();
            } else {
                recognizer.writeAudio(buffer, 0, buffer.length);
                recognizer.stopListening();
                if (!latch.await(5000, TimeUnit.MILLISECONDS)) { // 等待超过5000ms则自行结束等待
                    LOGGER.warn("Recognition timed out.");
                }
                return curRet.toString();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private RecognizerListener recListener = new RecognizerListener() {
        @Override
        public void onBeginOfSpeech() {
            LOGGER.info("onBeginOfSpeech enter");
        }
        @Override
        public void onEndOfSpeech() {
            LOGGER.info("onEndOfSpeech enter");
        }

        @Override
        public void onResult(RecognizerResult results, boolean isLast) {
            LOGGER.info("onResult enter");

            String text = results.getResultString();
            curRet.append(text);

            if (isLast) {
                latch.countDown(); // 唤醒等待的线程
            }
        }

        @Override
        public void onVolumeChanged(int volume) {
            LOGGER.info("onVolumeChanged volume=" + volume);
        }

        @Override
        public void onError(SpeechError error) {
            LOGGER.error("onError enter");
            if (null != error) {
                LOGGER.error("onError Code：" + error.getErrorCode() + "," + error.getErrorDescription(true));
            }
        }

        @Override
        public void onEvent(int eventType, int arg1, int agr2, String msg) {
            LOGGER.info("onEvent enter");
        }
    };
}
